package org.yst.spring.wechat;


import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.Method;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.yst.web.utils.UrlUtil;
import lombok.Getter;
import org.yst.spring.wechat.login.RequestLogin;
import org.yst.spring.wechat.login.ResponseLogin;
import org.yst.spring.wechat.phone.PhoneInfo;
import org.yst.spring.wechat.phone.ResponsePhoneInfo;

import java.util.HashMap;
import java.util.Map;

public class WechatUtils {

    private static WechatConfig wechatConfig;

    @Getter
    private static ResponseToken token;
    public static void setConfig(WechatConfig config){
        wechatConfig=config;
    }
    public static void refreshToken(){
        HttpRequest httpRequest=HttpRequest.of(UrlBuilder.ofHttp("https://api.weixin.qq.com/cgi-bin/stable_token "))
                .method(Method.POST)
                .body(JSONUtil.toJsonStr(new RequestTokenParam().setAppid(wechatConfig.getAppId())
                        .setSecret(wechatConfig.getSecretKey())
                        .setGrant_type("client_credential")));
        try(HttpResponse response=httpRequest.execute())
        {
            if (response.getStatus()== HttpStatus.HTTP_OK){
               token=JSONUtil.toBean(response.body(), ResponseToken.class);
            }
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    public static void forceRefreshToken(){
        HttpRequest httpRequest=HttpRequest.of(UrlBuilder.ofHttp("https://api.weixin.qq.com/cgi-bin/stable_token"))
                .method(Method.POST)
                .body(JSONUtil.toJsonStr(new RequestTokenParam().setAppid(wechatConfig.getAppId())
                        .setSecret(wechatConfig.getSecretKey())
                        .setForce_refresh(true)
                        .setGrant_type("client_credential")));
        try(HttpResponse response=httpRequest.execute())
        {
            if (response.getStatus()== HttpStatus.HTTP_OK){
                token=JSONUtil.toBean(response.body(), ResponseToken.class);
            }
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public static ResponseLogin login(String loginCode){
        RequestLogin requestLogin=new RequestLogin()
                .setAppid(wechatConfig.getAppId())
                .setSecret(wechatConfig.getSecretKey())
                .setJs_code(loginCode);
        String loginUrl="https://api.weixin.qq.com/sns/jscode2session?"+
                UrlUtil.ObjectToUrlParams(requestLogin);
        HttpRequest httpRequest=HttpRequest.of(
                UrlBuilder.ofHttp(loginUrl))
                .method(Method.GET);
        try(HttpResponse response=httpRequest.execute())
        {
            if (response.getStatus()== HttpStatus.HTTP_OK){
                ResponseLogin result= JSON.parseObject(response.body(),ResponseLogin.class);
                if (null==result.getErrcode()||result.getErrcode()==0){
                    return result;
                }
                throw new RuntimeException(result.getErrmsg());
            }
            throw new RuntimeException("wechat login error:"+response.getStatus());
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public static PhoneInfo getPhoneInfo(String phoneCode){
        Map<String,String> params=new HashMap<>();
        params.put("code",phoneCode);
        HttpRequest httpRequest=HttpRequest.of(
                        UrlBuilder.ofHttp("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+
                                token.getAccess_token()))
                .method(Method.POST)
                .body(JSON.toJSONString(params));
        try(HttpResponse response=httpRequest.execute())
        {
            if (response.getStatus()== HttpStatus.HTTP_OK){
                ResponsePhoneInfo result= JSON.parseObject(response.body(),ResponsePhoneInfo.class);
                if (result.getErrcode()==0){
                    return result.getPhone_info();
                }
                throw new RuntimeException(result.getErrmsg());
            }
            throw new RuntimeException("wechat getPhoneInfo error:"+response.getStatus());
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
    }

}
